//
//  FDMsgViewController.m
//  FD
//
//  Created by Yasin on 2018/10/13.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//
/**
 自定义作画按钮样式
 iOS11之后适用链接：https://www.jianshu.com/p/a6754dc1ae2a
 iOS11之前适用 ：https://www.jianshu.com/p/f942f203f824
 */

#import "FDMsgViewController.h"

//view
#import "HomeMsgCell.h" //cell h:180
#import "FDNowDataView.h" //无数据占位图
//model
#import "PushMsgModel.h"

//tools
#import "RBDataBaseManager.h" //数据库
#import "FDPushWebSocketTool.h" //1-14

//controller
#import "FDWebViewController.h" //跳转网页

@interface FDMsgViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tv;
@property (nonatomic, strong) NSMutableArray *dataArr;
/**无数据占位图*/
@property (nonatomic, strong) FDNowDataView *nodataView;
/**iOS11自定义左滑按钮样式需要记录对应的下标*/
@property (nonatomic, strong) NSIndexPath *editingIndexPath;
@end


@implementation FDMsgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    
//    [self initDataArray];
    [self readLocalDatabaseData]; //1-5
    [self loadHtmlTemplatePUSH]; //1-5
    
    //1-14
//    [[FDPushWebSocketTool defaultFdWebPushSockcet] setupAndOpenPushWebSocket];
}

- (void)setupUI {
    NSString *msgStr = NSLocalizedString(L_Message, @"消息");
    NSString *qbydStr = NSLocalizedString(L_ReadAll, @"全部已读");
    self.navigationItem.title = msgStr;
    //左边全部已读
    UIButton *readAllBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    readAllBtn.frame = CGRectMake(0, 0, 100, 30);//真机iOS10不给frame不显示
    [readAllBtn setTitle:qbydStr forState:(UIControlStateNormal)];
    [readAllBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    readAllBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight; //按钮内容右对齐2019-2-16
    readAllBtn.titleLabel.font = [UIFont systemFontOfSize:16.0]; //设置字体2019-2-16
    
    [readAllBtn addTarget:self action:@selector(readAllAction) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:readAllBtn];
    
    self.tv.frame = self.view.bounds;
    [self.view addSubview:self.tv];
    self.tv.tableFooterView = [UIView new];
    
    [self.view addSubview:self.nodataView];
}

- (void)initDataArray {
    for (int i = 0; i< 10; i++) {
        NSString *strI = [NSString stringWithFormat:@"%d",i];
        
        [self.dataArr addObject:strI];
    }
}

//!!!!:全部已读
- (void)readAllAction {
    FDLog(@"点击了,全部已读");
    //1.更新数据库
    [[RBDataBaseManager shareDataBaseQueueManager] updateReadAll:YES];
    //2.重新查一遍
    [self readLocalDatabaseData];
}

#pragma mark - getter
- (UITableView *)tv {
    if (!_tv) {
        _tv = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        //代理
        _tv.delegate = self;
        _tv.dataSource = self;
        
        //注册cell
        [_tv registerNib:[UINib nibWithNibName:@"HomeMsgCell" bundle:nil] forCellReuseIdentifier:@"HomeMsgCell"];
        
        //取消线
        _tv.separatorStyle = UITableViewCellSelectionStyleNone;
    }
    return _tv;
}

- (FDNowDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[FDNowDataView alloc] initWithFrame:self.view.bounds];
        [_nodataView changeTipsToNoMessageYet]; //2019-2-23
    }
    return _nodataView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}


#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeMsgCell *msgCell = [tableView dequeueReusableCellWithIdentifier:@"HomeMsgCell"];

    PushMsgModel *msgModel = self.dataArr[indexPath.row];
    //赋值
    msgCell.model = msgModel;
    
    return msgCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 220;
}

//1-5点击了cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PushMsgModel *selectModel = self.dataArr[indexPath.row];
    selectModel.isRead = YES;
    self.dataArr[indexPath.row] = selectModel;
    
    [self.tv reloadData];
    //更新数据库内容
    [[RBDataBaseManager shareDataBaseQueueManager] updateReadStateWithMsgId:selectModel.messageId];
    FDLog(@"选中的model是:%@",selectModel);
//    //点击跳转webveiw
    FDWebViewController *webViewVC = [[FDWebViewController alloc] init];
    webViewVC.resource = selectModel.resource;
    [self.navigationController pushViewController:webViewVC animated:YES];
}


#pragma mark - 自定义左滑编辑样式
//!!!!:iOS11之前的自定义样式
//需要结合自定义cell的insetrxxx:方法进行设置
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self xxxDeleteModelWithSelectIndexPath:indexPath];
    }
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    for (UIView * sv in cell.subviews) {
        FDLog(@"111:%@", sv);
    }
}


//!!!!:iOS11之后适用。
//适配有问题。图片始终会被渲染成灰色的。暂时无解。
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)){
    //删除
    if (@available(iOS 11.0, *)) {
       //删除
        UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:(UIContextualActionStyleDestructive) title:@"" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            FDLog(@"删除按钮");
            [self xxxDeleteModelWithSelectIndexPath:indexPath];
        }];
        
        //直接继承自NSObject 暂缓解决1-21.
//        deleteRowAction.image = [UIImage imageNamed:@"redDelete"]; //有毒。设置的图片都变成白色的。就是个废物。越写问题越多
        deleteRowAction.backgroundColor = [UIColor whiteColor];
        
        UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
        return config;
    } else {
        return nil;
        // Fallback on earlier versions
    }
}
//链接：https://www.jianshu.com/p/a6754dc1ae2a
//链接：https://www.jianshu.com/p/14d778afeefc


- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (self.editingIndexPath) {
        [self configSwipeButtons];
    }
}
- (void)configSwipeButtons {
    // 获取选项按钮的reference
    if (@available(iOS 11.0, *)) {
        // iOS 11层级 (Xcode 9编译): UITableView -> UISwipeActionPullView
        for (UIView *subview in self.tv.subviews)  {
//            FDLog(@"22:%@",subview);
            if ([subview isKindOfClass:NSClassFromString(@"UISwipeActionPullView")] ) {
                // 和iOS 10的按钮顺序相反
                UIButton *deleteButton = [subview.subviews firstObject];
                [self configDeleteButton:deleteButton];
            }
        }
    }
}
- (void)configDeleteButton:(UIButton*)deleteButton {
    if (deleteButton) {
        [deleteButton setImage:[UIImage imageNamed:@"redDelete"] forState:UIControlStateNormal];
    }
}
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    self.editingIndexPath = indexPath;
    [self.view setNeedsLayout];   // 触发-(void)viewDidLayoutSubviews
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    self.editingIndexPath = nil;
}







//!!!!:删除本地数据库
- (void)xxxDeleteModelWithSelectIndexPath:(NSIndexPath *)indexPath {
    //从数据中删除
    PushMsgModel *model = self.dataArr[indexPath.row];
    [[RBDataBaseManager shareDataBaseQueueManager] deleteMessageModelMsgId:model.messageId];
    //更新数据
    [self readLocalDatabaseData];
    
    
}



#pragma mark - private
/*读取本地数据库*/
- (void)readLocalDatabaseData {
    
    [self.dataArr removeAllObjects]; //移除之前数据
    
    NSArray *tempArr = [[RBDataBaseManager shareDataBaseQueueManager] selectAllMessage];
    
    self.dataArr = [NSMutableArray arrayWithArray:tempArr];
    
    if (self.dataArr.count) {
        self.nodataView.hidden = YES;
    }else {
        self.nodataView.hidden = NO;
    }
    
    [self.tv reloadData];
}


/**删除*/
/**修改状态*/
/**批量修改状态*/

/**A.下载消息推送html模板*/
- (void)loadHtmlTemplatePUSH {
 
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [FDHttpAPi requestHtmlTemplatePushSuccessBlock:^(id responseObjc) {
        
        [hud hideAnimated:YES];
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSString *template = responseObjc[@"data"][@"template"];
        
            //B.使用AWS下载模板 保存到本地
            
            [FDAWSDownUpLoadTool fdAWSDownloadWithKey:template complectionBlock:^(NSString * _Nonnull resultStr) {
                //C.轮播图模板字符串保存到本地
                [FDWebViewHtmlTool fdSavePushMsgHtmlTemplate:resultStr];
            } failBlock:^{
                
            }];
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        [hud hideAnimated:YES];
        FDLog(@"%@",[error localizedDescription]);
    }];
}

/**
 {"event":"SUCCESS","data":{"template":"public/3bd9689868ac41f89992a243340e6053"},"describe":""}
 */
//A、先下载模板
//B、在线resource
//C、替换为resource内容
//D、加载网页
/**
 2.一键已读
 
 收到消息显示小圆点
 删除从本地移除
 全部已读 修改读写状态为已读,国际化文字自适应。
 */

@end
